package com.lemon.smartsafety.ui.fragment.fire;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;

import com.google.gson.reflect.TypeToken;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.mode.adapter.LampMode;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.FireListMode;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseFragment;
import com.lemon.smartsafety.ui.activity.fire.FirefightingUtil;
import com.lemon.smartsafety.ui.activity.fire.item.situation.PersonalSituationActivity;
import com.lemon.smartsafety.ui.adapter.fire.LampCenterAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.view.ViewFireCompanyNone;
import com.lemon.smartsafety.view.list.ListRefreshView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 项目名称：workspace
 * 类描述：
 * 创建人：Fargo
 * 创建时间：2016/8/11 13:24
 * 修改人：Fargo
 * 修改时间：2016/8/11 13:24
 * 修改备注： 按周期分类
 */
public class FireCycleFragment extends NewBaseFragment {


    @Bind(R.id.listView)
    ListRefreshView listView;
    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;
    @Bind(R.id.viewFireCompanyNone)
    ViewFireCompanyNone viewFireCompanyNone;


    private LampCenterAdapter lampCenterAdapter;
    private List<LampMode> mList;
    private LampMode lampMode;

    private List<FireListMode> fireListModeList;
    private List<FireListMode> fireList;

    private SuperviseCompanyResult.ResultEntity resultEntity;


    @Override
    protected void getBundleArgs() {
        if (getArguments().containsKey(BundleKey.FIRE_COMPANY_BASE_INFO)) {
            resultEntity = (SuperviseCompanyResult.ResultEntity) getArguments().getSerializable(BundleKey.FIRE_COMPANY_BASE_INFO);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_firefighting_statistics;
    }

    @Override
    protected void initView() {

        fireList = new ArrayList<>();
        fireListModeList = new ArrayList<>();
        mList = new ArrayList<>();
        //mList.add(new LampMode(0,"日巡查任务","45/108",true,R.drawable.shape_circle_red));
        // mList.add(new LampMode(0,"月巡查任务","12/15",true,R.drawable.shape_circle_yellow));
        lampCenterAdapter = new LampCenterAdapter(mActivity, mList);
        lampCenterAdapter.setShowArrowRight(false);
        listView.setAdapter(lampCenterAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                intent = new Intent(mActivity, PersonalSituationActivity.class);
                bundle = new Bundle();
                //（1：按检查周期；2：按检查场所）
                bundle.putString(BundleKey.FIRE_CHECK_TYPE, "1");
                bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
                bundle.putSerializable(BundleKey.FIRE_PERSONAL_DATA, fireList.get(position));
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

        initSwipRefresh(swipeLayout);
        //initLoadeRefresh(listView);
    }

    @Override
    protected void initHttp() {
        initList();
    }

    @Override
    protected void initList() {
        current_page = 1;
        httpList();
    }

    @Override
    protected void loadList() {

    }

    @Override
    protected void refreshView() {

    }

    /**
     * 错误的情况下 刷新
     */
    public void errorView(String title) {

        try {
            if (CommonUtil.listIsEmpty(mList)) {
                viewFireCompanyNone.setVisibility(View.VISIBLE);
                showSwipLayout(swipeLayout, false);
                if (CommonUtil.strIsEmpty(title)) {
                    viewFireCompanyNone.setContent("没有更多数据");
                    viewFireCompanyNone.setSearch("重试");
                } else {
                    viewFireCompanyNone.setContent(title);
                    viewFireCompanyNone.setSearch("重试");
                }
                viewFireCompanyNone.setAllClick(new ViewFireCompanyNone.AllClick() {
                    @Override
                    public void click() {
                        initList();
                    }
                });
            } else {
                viewFireCompanyNone.setVisibility(View.GONE);
                showSwipLayout(swipeLayout, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void callFinish() {

    }

    @Subscribe
    public void onEventMainThread(RefreshViewEntity refreshViewEntity) {
        //刷新View
        if (refreshViewEntity.getTAG().equals(FireCycleFragment.class.getName())) {
            if (CommonUtil.objIsEmpty(fireListModeList)) {
                initList();
            }
        } else if (refreshViewEntity.getTAG().equals(RefreshViewEntity.REFRESH_TAG)) {
            try {
                initList();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    private void httpList() {
        if (!bPutHttp) {
            bPutHttp = true;
            LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
            params.put("page_size", String.valueOf(page_size));
            params.put("current_page", String.valueOf(current_page));

            params.put("company_code", resultEntity.getCompanyCode());
            params.put("check_type", "1");


            showLoading("");
            HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_resumption_detail), "", new HttpOkBase.HttpInterface() {
                @Override
                public void callBackFunction(boolean httpClient, String result) {

                    dismissLoading();
                    bPutHttp = false;
                    if (httpClient) {
                        BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                        if (!CommonUtil.objIsEmpty(baseMode)) {
                            if (HttpBack.httpBackError(baseMode)) {

                                try {
                                    fireListModeList = mGson.fromJson(mGson.toJson(baseMode.getResult()), new TypeToken<List<FireListMode>>() {
                                    }.getType());
                                    transList();
                                    fireList.addAll(fireListModeList);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } else {
                                errorView(baseMode.getMsg());
                                ToastUtil.show(baseMode.getMsg());
                            }
                            lampCenterAdapter.notifyDataSetChanged();
                        }
                    } else {
                        fireListModeList = null;
                        errorView("网络连接失败");
                    }
                }
            });
        }

    }


    /**
     * 转换list
     */
    private void transList() {

        if (current_page == 1) {
            mList.clear();
            fireList.clear();
        }


        for (int i = 0; i < fireListModeList.size(); i++) {
            lampMode = new LampMode(0, fireListModeList.get(i).getTypeName(), fireListModeList.get(i).getConformNum() + "/" + fireListModeList.get(i).getAllCount(), true, FirefightingUtil.getScoreImgCircleColor(fireListModeList.get(i).getStatus()));
            switch (fireListModeList.get(i).getTypeName()) {
                case "hour":
                    lampMode.setTitle("时巡查任务");
                    break;
                case "day":
                    lampMode.setTitle("日巡查任务");
                    break;
                case "year":
                    lampMode.setTitle("年巡查任务");
                    break;
                case "month":
                    lampMode.setTitle("月巡查任务");
                    break;
            }
            mList.add(lampMode);

        }
        lampCenterAdapter.notifyDataSetChanged();

        errorView("");
    }


}
